package han.cirno.corrupt.components.school

import han.cirno.corrupt.data.DataKeys
import han.cirno.corrupt.data.instances.UserSchoolData
import han.cirno.corrupt.compose.preferenceFlow
import han.cirno.corrupt.components.school.impl.fafu.FafuSchool
import han.cirno.corrupt.components.school.impl.fjut.FjutSchool
import han.cirno.corrupt.components.school.impl.mju.MjuSchool
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking

class SchoolImpl{
    companion object{
        private val schoolInstances=HashMap<UserSchoolData.School, SchoolProvider>()
        private val schoolFlow by lazy { preferenceFlow(DataKeys.DATA_SCHOOL,UserSchoolData.School.None.name){ UserSchoolData.School.valueOf(it)} }
        val impl: SchoolProvider?
            get()= getImpl()
        fun getImpl(school: UserSchoolData.School?=null): SchoolProvider?{
            var targetSchool:UserSchoolData.School?=school
            if (school==null)
                targetSchool= runBlocking { schoolFlow.first() }
            if(schoolInstances.contains(targetSchool))
                return schoolInstances[targetSchool]
            val impl=when(targetSchool){
                UserSchoolData.School.None->null
                UserSchoolData.School.FAFU-> FafuSchool()
                UserSchoolData.School.MJU-> MjuSchool()
                UserSchoolData.School.FJUT-> FjutSchool()
                else -> return null
            }
            return impl?.also { schoolInstances[targetSchool]=it }
        }
    }
}